package com.shy.plugin.seo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gson.Gson;
import com.shy.base.util.StringUtils;
import com.shy.cms.entity.Site;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.Method;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BingPost {

	private static String bingApiUrl = "http://api.indexnow.org/IndexNow"; 
	
	private static Gson gson = new Gson();
	
    /**
     * baidu post
     * @param urls  链接列表
     * @param params 参数
     * @return
     * @throws IOException   
     * @date: 2020年3月4日 下午9:37:14
     */
    public static String postUrl(List<String> urls, Map<String, Object> params) throws IOException {
		Set<String> set = new HashSet<String>(urls);
		urls = new ArrayList<String>(set);
		Site site = (Site) params.get("site");
		if (!StringUtils.isNotBlank(site.getBingToken())) {
			return "必应key未维护";
		}
		String result = "";
		if (StringUtils.isNotEmpty(site.getmBaseUrl())) {
			// 有移动端时拆分提交
			List<String> pcList = new ArrayList<String>();
			List<String> mList = new ArrayList<String>();
			for (String url : urls) {
				if (url.indexOf(site.getmBaseUrl()) >= 0) {
					mList.add(url);
				} else {
					pcList.add(url);
				}
			}
			if(!pcList.isEmpty()) {
				params.put("urlType", "pc");
				result += "【pc提交】：" + postUrlByUrlType(pcList, params);
			}
			if(!mList.isEmpty()) {
				params.put("urlType", "m");
				result += "【m提交】：" + postUrlByUrlType(mList, params);
			}
		} else {
			params.put("urlType", "pc");
			result += postUrlByUrlType(urls, params);
		}
		return result;
    }
    
    
    /**
     * baidu post
     * @param urls  链接列表
     * @param params 参数
     * @return
     * @throws IOException   
     * @date: 2020年3月4日 下午9:37:14
     */
    public static String postUrlByUrlType(List<String> urls, Map<String, Object> params) throws IOException {
        Set<String> set = new HashSet<String>(urls);
        urls = new ArrayList<String>(set);
    	Site site = (Site) params.get("site");
		//默认pc端
        String host = site.getBaseUrl();
        //如果是m端，必应提交host都使用主站
        /*if(params.containsKey("urlType") && "m".equals(params.get("urlType").toString()) 
                && StringUtils.isNotEmpty(site.getmBaseUrl())) {
            host = site.getmBaseUrl();
        }*/
        if(host.startsWith("http://")) {
            host = host.substring(7);
        }
        if(host.startsWith("https://")) {
            host = host.substring(8);
        }
        return postBing(urls, host, site.getBingToken());
    }
    
    
    /**
     * 必应提交
     * POST /IndexNow HTTP/1.1
		Content-Type: application/json; charset=utf-8
		Host: api.indexnow.org
		{
		  "host": "www.example.org",
		  "key": "5da75c8bb2ac468ba77a3ef9d217e7e3",
		  "keyLocation": "https://www.example.org/5da75c8bb2ac468ba77a3ef9d217e7e3.txt",
		  "urlList": [
		      "https://www.example.org/url1",
		      "https://www.example.org/folder/url2",
		      "https://www.example.org/url3"
		      ]
		}
     * @param urls
     * @param host
     * @param token
     * @return
     */
    public static String postBing(List<String> urls, String host, String token) {
        String result = "";
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("host", host);
            paramMap.put("key", token);
            paramMap.put("urlList", urls);
            HttpResponse response = HttpRequest.post(bingApiUrl).body(gson.toJson(paramMap), "application/json").execute();
            
            if (HttpStatus.HTTP_OK == response.getStatus()) {
            	result = "必应提交成功";
            } else {
            	result = StrUtil.format("必应提交失败:{}:{}", response.getStatus(), response.body());
            }
            System.out.println(result);
        } catch (Exception e) {
            //e.printStackTrace();
        	log.error("bing post error:{}", e);
        }
        return result;
    }
    
    
    public static void main(String[] args) {
        List<String> urls = new ArrayList<String>();
        urls.add("https://www.zztcc.com/news/240806/1883.html");
        //urls.add("https://www.znwx.cn/lang/mziy2oy3.html");
        //urls.add("https://www.znwx.cn/ai/jpyc8z8o.html");
        postBing(urls, "www.zztcc.com", "53d757f1bab741c1b1e1d8683a24bdb5");
    }
    
	
}
